package com.mzj.saas.mservice.qiyuesuo.service;

import com.mzj.saas.mservice.qiyuesuo.vo.ContractPageUrlVO;
import com.mzj.saas.mservice.qiyuesuo.vo.ElectronicContractVO;
import com.mzj.saas.redis.RedisService;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.Seal;
import com.qiyuesuo.sdk.v2.bean.User;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.param.SignParam;
import com.qiyuesuo.sdk.v2.request.*;
import com.qiyuesuo.sdk.v2.response.ContractPageResult;
import com.qiyuesuo.sdk.v2.response.ContractShorturlResult;
import com.qiyuesuo.sdk.v2.response.SdkResponse;
import com.qiyuesuo.sdk.v2.response.SealListResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 契约锁接口-印章/签署
 *
 * @author hp
 */
@Service
public class QiYueSuoSealService {

    private Logger logger = LoggerFactory.getLogger(QiYueSuoSealService.class);
    private String SEAL_NAME_KEY = "contract.seal.name";

    @Autowired
    private SdkClient sdkClient;
    @Autowired
    private RedisService redisService;

    /**
     * 获取企业印章, 默认取第一个印章
     *
     * @param orgId      企业id
     * @param tenantName 子公司名称
     * @return
     * @author shun
     * @date 2021年6月11日
     */
    public Long getOrgSeal(Long orgId, String tenantName) {
        // 查询缓存, 如果缓存未找到, 查询接口
        Long sealId = redisService.getOrgSealId(orgId);
        if (sealId != null) {
            return sealId;
        }

        String sealName = redisService.getValue(SEAL_NAME_KEY);
        List<Seal> list = getSealList(tenantName);
        for (Seal seal : list) {
            if (seal.getName().equals(sealName)) {
                redisService.putOrgSealId(orgId, seal.getId());
                return seal.getId();
            }
        }

        if (list.isEmpty()) {
            return null;
        }

        redisService.putOrgSealId(orgId, list.get(0).getId());
        return list.get(0).getId();
    }

    /**
     * 印章列表
     *
     * @param tenantName 查询条件：子公司名称，若传递了则查询子公司下的印章，默认为平台方主公司
     */
    public List<Seal> getSealList(String tenantName) {
        SealListRequest request = new SealListRequest();
        if (tenantName != null) {
            request.setTenantName(tenantName);
        }
        String response = sdkClient.service(request);
        SdkResponse<SealListResult> responseObj = JSONUtils.toQysResponse(response, SealListResult.class);
        if (responseObj.getCode() == 0) {
            SealListResult sealList = responseObj.getResult();
            return sealList.getList();
        } else {
            logger.info("印章列表失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
            return new ArrayList<Seal>();
        }
    }

    /**
     * 签署公章
     *
     * @param contractId 合同id
     * @param sealId     印章id
     * @param tenantName 子公司名称
     * @return 0:成功
     */
    public Integer contractCompanysign(Long contractId, Long sealId, String tenantName) {
        // 签署公章
        SignParam param = new SignParam();
        param.setContractId(contractId);
        param.setSealId(sealId);
        if (StringUtils.isNotBlank(tenantName)) {
            param.setTenantName(tenantName);
        }
        ContractSignCompanyRequest request = new ContractSignCompanyRequest(param);
        String response = sdkClient.service(request);
        SdkResponse<Object> responseObj = JSONUtils.toQysResponse(response);
        if (responseObj.getCode() == 0) {
            logger.info("公章签署成功");
        } else {
            logger.info("公章签署失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
        return responseObj.getCode();
    }

    /**
     * 签署法人章
     *
     * @return 0:成功
     */
    public Integer contractLegalpersonsign(ElectronicContractVO vo) {
        // 签署法人章
        SignParam param = new SignParam();
        param.setContractId(vo.getContractId());

        if (StringUtils.isNotBlank(vo.getTenantName())) {
            param.setTenantName(vo.getTenantName());
        }

        ContractSignLpRequest request = new ContractSignLpRequest(param);
        String response = sdkClient.service(request);
        SdkResponse<Object> responseObj = JSONUtils.toQysResponse(response);
        if (responseObj.getCode() == 0) {
            logger.info("法人章签署成功");
        } else {
            logger.info("法人章签署失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
        return responseObj.getCode();
    }

    /**
     * 签署页面
     *
     * @param vo
     * @return 文件签署页面，链接有效期30分钟
     */
    public String contractPageurl(ContractPageUrlVO vo) {
        // 合同页面
        ContractPageRequest request = new ContractPageRequest();

        request.setContractId(vo.getContractId());

        if (StringUtils.isNotBlank(vo.getTenantName())) {
            request.setTenantName(vo.getTenantName());
        }

        if (StringUtils.isNotBlank(vo.getCallbackPage())) {
            request.setCallbackPage(vo.getCallbackPage());
        }

        if (StringUtils.isNotBlank(vo.getContact()) && StringUtils.isNotBlank(vo.getContactType())) {
            request.setUser(new User(vo.getContact(), vo.getContactType()));
        }
        String response = sdkClient.service(request);
        SdkResponse<ContractPageResult> responseObj = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (responseObj.getCode() == 0) {
            ContractPageResult result = responseObj.getResult();
            logger.info("合同页面地址为:{}", result.getPageUrl());
            return result.getPageUrl();
        } else {
            logger.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
        return null;
    }

    /**
     * 获取合同的签署短链接
     *
     * @param contractId 合同ID
     * @param tenantName 子公司名称，若使用业务ID获取访问短链接，且合同是以子公司身份创建的，则需要传递该值，用于确定合同主体
     * @param contact    指定登陆账号，支持邮箱和手机联系方式
     * @return
     */
    public String contractShorturl(Long contractId, String tenantName, String contact) {
        ContractShorturlRequest request = new ContractShorturlRequest(contractId);
        if (StringUtils.isNotBlank(tenantName)) {
            request.setTenantName(tenantName);
        }
        if (StringUtils.isNotBlank(contact)) {
            request.setContact(contact);
        }
        String response = sdkClient.service(request);
        SdkResponse<ContractShorturlResult> responseObj = JSONUtils.toQysResponse(response,
                ContractShorturlResult.class);
        if (responseObj.getCode() == 0) {
            ContractShorturlResult result = responseObj.getResult();
            logger.info("合同短链接为:{}", result.getShorturl());
            return result.getShorturl();
        } else {
            logger.info("请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
        }
        return null;
    }
}
